package leetcode.editor.cn.dsa09_doublequeue;
//给定一个字符串，逐个翻转字符串中的每个单词。

public class ReverseWordsInAString151_4 {
    public static void main(String[] args) {
        ReverseWordsInAString151_4.Solution solution = new ReverseWordsInAString151_4().new Solution();
        System.out.println(solution.reverseWords("the sky is blue"));
        System.out.println(solution.reverseWords("  hello world!  "));
        System.out.println(solution.reverseWords("a good   example"));
        System.out.println(solution.reverseWords("  Bob    Loves  Alice   "));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 解法五：切割+反向遍历
         * 1.将字符串按空格进行切割
         *   按单个字符"空格"切割，降低处理复杂度
         *   切割结果是一个字符串数组，可能包含""
         * 2.反向遍历数组中的每个单词
         * 3.将每个单词存入字符串缓冲区中
         *   存入前加空格作为前缀
         *   遍历完成后进行截取
         *
         * @param s
         * @return
         */
        public String reverseWords(String s) {
            if (s == null || "".equals(s = s.trim())) {
                return "";
            }
            // 按空格进行切割，而不是 \s+，降低复杂度
            String[] strings = s.split(" ");
            StringBuilder sb = new StringBuilder();
            // 反向遍历
            for (int i = strings.length - 1; i >= 0; i--) {
                // 拼接一个空格+单词
                if (strings[i].length() != 0) {
                    sb.append(" ").append(strings[i]);
                }
            }
            // 截掉第一个空格
            return sb.substring(1);
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)
}
